﻿using DataType;
using DataType.Actions;
using DataType.CustomEnumType;
using DataType.JudgeResults;
using DataType.MessageType;
using MapCalclator;
using OprsSimulator.Operators;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace ActionsJudge
{
    public static class ActionsJudge
    {
        public static List<IJudgeResult> ToJudge(List<IBasicAction> actions, List<IOperator> oprs, List<IOperator> passengers, Map map, CityMsg[] cities, ShootJudgeTable shootJudgeTable)
        {
            List<IJudgeResult> judgeResults = new List<IJudgeResult>();

            // 针对Acts中的每一个Act的type，调用不同的裁决函数，逐个裁决
            foreach (var act in actions)
            {
                if (Enum.TryParse<ActionType>(act.Type.ToString(), out ActionType actionType))
                {
                    List<IJudgeResult> curJudgeResults = new List<IJudgeResult>();
                    // 单独列出射击动作裁决，因为需要使用裁决表
                    if (actionType == ActionType.Shoot)
                    {
                        curJudgeResults = ShootJudge.ToJudge(act, oprs, map, shootJudgeTable);
                    }
                    else if(actionType == ActionType.Occupy)
                    {
                        curJudgeResults = OccupyJudge.ToJudge(act, oprs, map, cities);
                    }
                    else if (actionType == ActionType.GetOff)
                    {
                        curJudgeResults = GetOffJudge.ToJudge(act, oprs, passengers, map);
                    }
                    else
                    {
                        // 使用反射机制确定静态方法，然后进行调用（这段代码还需要验证）
                        string actionName = MethodBase.GetCurrentMethod().DeclaringType.Namespace + "." + actionType.ToString();
                        string actionJudgeClassName = actionName + "Judge";
                        //string _ToJudgeMethodName = actionJudgeClassName + ".ToJudge";
                        MethodInfo _ToJudgeMethod = Type.GetType(actionJudgeClassName).GetMethod("ToJudge");
                        if (_ToJudgeMethod == null) Trace.TraceError($"找不到该ToJudge方法，请核查！");
                        object[] paras = new object[] { act, oprs, map };  // 在此处增加参数
                        curJudgeResults = (List<IJudgeResult>)_ToJudgeMethod.Invoke(null, paras);
                    }

                    judgeResults.AddRange(curJudgeResults);
                }
                else Trace.TraceError($"动作的类型{act.Type.ToString()}有误！");
            }

            return judgeResults;
        }
    }
}
